<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="./js/promiseAjax.js"></script>
    <script src="./js/cookie.js"></script>
    <link rel="stylesheet" href="./css/userdit.css">
</head>
<body>
<h1>用户修改页面</h1>
<form action="" class="top">
    头像：
    <img src="" alt="">
    <input type="file" name='avatar'>
    <br>
    用户名：<input type="text" name="username">
    <br>
    邮箱：<input type="email" name="email">
    <br>
    <input type="submit">
</form>
</body>
<script>
// 获取标签
var usernameInput = document.querySelector('[name="username"]')
var emailInput = document.querySelector('[name="email"]')
var avatarInput = document.querySelector('[name="avatar"]')
// 发请求获取用户信息展示在表单中
request({
    url: '/api/users/getUsers/' + getCookie('userid'),
    headers: {
        Authorization: localStorage.getItem('token')
    }
}).then(res => {
    console.log(res);
    usernameInput.value = res.data.username
    emailInput.value = res.data.email
    document.querySelector('img').src = res.data.avatar
})

document.querySelector('form').onsubmit = function() {
    var username = usernameInput.value
    var email = emailInput.value
    console.dir(avatarInput);
    // ajax要提交数据带有文件信息 - formData
    var formdata = new FormData()
    formdata.append('username', username)
    formdata.append('email', email)
    formdata.append('avatar', avatarInput.files[0])
    
    request({
        url: '/api/users/editUser/' + getCookie('userid'),
        method: 'put',
        data: formdata,
        headers: {
            Authorization: localStorage.getItem('token')
        }
    }).then(res => {
        console.log(res);
    })
    return false
}
/*
修改用户信息：
    获取用户信息，展示在页面中
    表单提交 - 包含了普通数据，也包含了文件信息
        获取要提交的数据 - formdata
            var formdata = new FormData()
            formdata.append(键, 值)
            formdata.append(文件的键, input.files[0])
        ajax提交表单数据，
            data: formdata
*/
</script>
</html>